package main

import (
	"log"
	"net"
	"net/http"
	"qqtestprotocol"

	"gitee.com/viplianghl/golib/liangtcp"
)

var g_bussiness bussiness
var g_tcpServer liangtcp.LiangTCPServer

func httpget_testlive(rw http.ResponseWriter, req *http.Request) {
	g_bussiness.Mon.testlive(rw, req)
}

func onConn(conn net.Conn) error {
	g_bussiness.Mon.ActiveConnCount++
	g_bussiness.Mon.TotalConnToday++
	return nil
}

func onDisconn(conn net.Conn) error {
	g_bussiness.Mon.ActiveConnCount--

	// 用户要反查一下
	g_bussiness.onDisconn(conn)
	return nil
}

func onMsg(conn net.Conn, buf []byte) error {
	log.Println("reve data (from ", conn.RemoteAddr().String(), "): ", string(buf))

	var cmd qqtestprotocol.Protocol_cmd
	err := qqtestprotocol.TransProtocol(buf, &cmd)
	if err != nil {
		log.Println("QQtest transProtocol cmd err: ", err)
		return err
	}

	switch cmd.Cmd {
	case "regist":
		return g_bussiness.Regist(conn, buf)
	case "login":
		return g_bussiness.Login(conn, buf)
	case "add":
		return g_bussiness.AddFriend(conn, buf)
	case "del":
		return g_bussiness.DelFriend(conn, buf)
	case "send":
		return g_bussiness.SendMsg(conn, buf)
	}

	return nil
}

func main() {
	err := g_bussiness.Init()
	if err != nil {
		log.Println("QQtest bussiness init err: ", err)
	}

	//
	g_tcpServer.OnConn = onConn
	g_tcpServer.OnDisconn = onDisconn
	g_tcpServer.OnMsg = onMsg
	go g_tcpServer.Listen(":8081")

	http.HandleFunc("/testlive", httpget_testlive)
	log.Fatal(http.ListenAndServe(":8083", nil))
}
